package com.itheima.health.filter;

import com.itheima.health.context.BaseText;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.service.impl.UserServiceImpl;
import com.itheima.health.utils.CookieUtil;
import com.itheima.health.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

//没有实现Filter接口，必须加web.xml配置或者@WebFilter注解
@Slf4j
@Order(1)
@WebFilter(filterName = "zindexAdminAuthorityFilter", urlPatterns = "/*")
public class ZindexAdminAuthorityFilter implements Filter {
    /*private PermissionDao permissionDao;
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("过滤器初始化");
        this.userService = SpringContextUtils.getBean("userService");
        this.permissionDao = SpringContextUtils.getBean(PermissionDao.class);
        //SpringContextUtils.getBean(HealthApplication.class)
    }*/

    /**
     * 过滤器
     * @param servletRequest   请求
     * @param servletResponse  响应
     * @param filterChain      过滤器链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器执行了");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();                            //获取请求路径
        log.info("请求路径：{}",requestURI);
        //http://localhost:9002/ordersetting/upload

        //利用工具类获取bean对象
        UserServiceImpl  userServiceImpl = (UserServiceImpl) SpringContextUtils.getBean("userServiceImpl");
        PermissionDao permissionDao = (PermissionDao)SpringContextUtils.getBean("permissionDao");




        //从cookie中获取当前用户id
        String string = CookieUtil.parseCookie(request);
        if(string != null){
            //将cookie中的id存入ThreadLocal
            BaseText.setCurrentId(Integer.parseInt(string));
        }


        //读取权限映射文件
        Properties properties = new Properties();
        InputStream asStream = this.getClass().getClassLoader().getResourceAsStream("AuthorityMap.properties");
        properties.load(asStream);
        //将所有权限属性存入map
        HashMap<String, String> map = (HashMap) properties.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().toString()
                ));
        //请求路径包含在map中，根据权限key判断当前用户是否可以访问
        for(Map.Entry<String, String> entry : map.entrySet()){
            if(requestURI.contains(entry.getValue())){//判断当前请求路径是否包含权限值
                String authority = entry.getKey();
                Integer userId =  BaseText.getCurrentId();
                log.info("过滤器当前用户id：{}",userId);
                //根据id查询职业
                //获取当前用户的职业，根据职业获取权限集合
                //UserServiceImpl userService = new UserServiceImpl();
                List<Integer> roleIds =  userServiceImpl.getJobByUserId(userId);
                //set集合接受权限，不会重复
                Set<String> permissions = new HashSet<>();
                if(roleIds.size()>0){
                    for(Integer roleId : roleIds){
                        //根据职业的id查询权限集合
                        permissions = permissionDao.findPermissionByRoleId(roleId);
                        if(permissions.contains(authority)){//放行
                            filterChain.doFilter(servletRequest,servletResponse);
                            return;
                        }
                    }
                }else {
                    log.info("权限不足");
                    response.setStatus(403);
                    throw new BusinessRuntimeException("权限不足");
                }
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);
        return;


    }
}
